﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Data;
using Data.implement;
using log4net;
using log4net.Repository.Hierarchy;
using LYWebsite.Convert;
using LYWebsite.Helper;
using LYWebsite.Models;
using Services;
using Services.Implement;
using Services.Interface;

namespace LYWebsite.Controllers
{
    public class ChargingController : Controller
    {
        ILog Logger = LogManager.GetLogger("");
        //
        // GET: /Charging/

        //public ActionResult Index()
        //{
        //    return View();
        //}
        public ActionResult InitUser(int CarId=0)
        {
            User user = DoInit(CarId);
            if (user == null)
                return Redirect("~/Result/Exception");
            return Redirect("~/Charging/ChargeThis?GUID=" + user.GUID);
        }

        private User DoInit(int carId)
        {
            WeiXinUser weixinUser = (WeiXinUser)Session["UserInfo"];
            if(weixinUser == null)
                return null;
            IAuthService authService = new AuthService();
            User user = authService.Login(carId, weixinUser);
            Session["CurrentUser"] = user;
            return user;
        }

        public ActionResult ChargeThis(string GUID = "")
        {
            try
            {
                IChargingService service = new ChargingService();
                string customerAddress = Request.UserHostAddress;
                if (string.IsNullOrEmpty(GUID))
                {
                    return Redirect("~/Result/Exception");
                }
                User user = Session["CurrentUser"] as User;
                if (user == null)
                {
                    user = service.GetUserByGUID(GUID);
                    if (user == null || user.UserId == 0)
                    {
                        return Redirect("~/Result/ErrorInfo");
                    }
                }
                else if (GUID == user.GUID)
                {
                    var tempUser = service.GetUserByGUID(user.GUID);
                    UserModel model = new UserModel(tempUser);
                    ViewData["username"] = model.userName;
                    ViewData["userimg"] = user.headimgurl;
                    return View("Share", model);
                }
                else
                {
                    
                    user = service.GetUserByGUID(GUID);
                }
                
                IInitPageService initPageService = new InitPageService();
                initPageService.AddShareRecord(customerAddress);
                ViewData["userimg"] = user.headimgurl;
                Session["targetid"] = user.UserId;
                ViewData["username"] = user.UserName;
                ViewData["carname"] = user.Car.CarName;
                ViewData["carimage"] = user.Car.ImageUrl;
                ViewData["locationimage"] = user.Location.ImageUrl;
                ViewData["locationname"] = user.Location.LocationName;
                ViewData["cardscription"] = user.Car.Description;
                ViewData["chargingtimes"] = user.ChargingTimes;
                ViewData["sex"] = user.sex;
                return View("ChargingView");
            }
            catch (Exception e)
            {
                Logger.Error("CharingThis has an error:"+e+"\n\r"+GUID);
                return Redirect("~/Result/Exception");
            }


        }

        private bool GetSessionWeiXinUser()
        {
            var httpCookie = Request.Cookies["userInfo"];
            if (httpCookie != null)
            {
                WeiXinUser userInfo = new WeiXinUser();
                userInfo.city = httpCookie["city"];
                userInfo.country = httpCookie["country"];
                userInfo.headimgurl = httpCookie["headimgurl"];
                userInfo.nickname = httpCookie["nickname"];
                userInfo.openId = httpCookie["openId"];
                userInfo.province = httpCookie["province"];
                userInfo.sex = httpCookie["sex"];
                Session["UserInfo"] = userInfo;
                return true;
            }
            return false;
        }

        public ActionResult RedirectToWeiXin()
        {
            try
            {
                if (GetSessionWeiXinUser())
                    return Redirect("~/Charging/DoCharge"); 
                string appid = ConfigurationSettings.AppSettings["appid"];
                string url = ConfigurationSettings.AppSettings["url"];
                return Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + url + "/Charging/" + "&response_type=code&scope=snsapi_userinfo&state=" + "#wechat_redirect");
            }
            catch (Exception e)
            {
                Logger.Error("CharingThis has an error:" + e);
                return Redirect("~/Result/Exception");
            }
        }
        public ActionResult DoCharge()
        {
            WeiXinUser weixinUser = (WeiXinUser)Session["UserInfo"];
            if (weixinUser == null)
                return RedirectToWeiXin();
            try
            {
                int targetId=0;
                var tempdata = Session["targetid"];
                if (tempdata!=null)
                {
                    int.TryParse(tempdata.ToString(), out targetId);
                }
                else
                {
                    return Redirect("~/Result/Exception");
                }
                
                if (targetId<=0)
                {
                    return Redirect("~/Result/Exception");
                }

                //var verifyResult = VerificationHelper.VerifyChargeLogin(chargeModel);
                //if (!string.IsNullOrEmpty(verifyResult))
                //    return View(verifyResult);

                IChargingService service = new ChargingService();
                ChargingResultEnum result = service.Charging(weixinUser, targetId);
                switch (result)
                {
                    case ChargingResultEnum.Successful:
                        return Redirect("~/Result/ChargingSuccessful");
                        break;
                    case ChargingResultEnum.OverLimitTimes:
                        return Redirect("~/Result/ChargingFailed1");
                        break;
                    case ChargingResultEnum.HaveCharging:
                        return Redirect("~/Result/ChargingFailed2");
                        break;
                    case ChargingResultEnum.AccountAuthFail:
                        return Redirect("~/Result/ChargingFailed3");
                        break;
                    case ChargingResultEnum.Exceptions:
                        return Redirect("~/Result/Exception");
                        break;
                    default:
                        Logger.Error("DoCharge has an error for result is "+result);
                        return Redirect("~/Result/Exception");

                }
            }
            catch (Exception e)
            {
                Logger.Error("DoCharge has an error:" + e);
                return Redirect("~/Result/Exception");
            }
            
        }


        ////
        //// GET: /Charging/Details/5

        //public ActionResult Details(int id)
        //{
        //    return View();
        //}

        ////
        //// GET: /Charging/Create

        //public ActionResult Create()
        //{
        //    return View();
        //}

        ////
        //// POST: /Charging/Create

        //[HttpPost]
        //public ActionResult Create(FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add insert logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        ////
        //// GET: /Charging/Edit/5

        //public ActionResult Edit(int id)
        //{
        //    return View();
        //}

        ////
        //// POST: /Charging/Edit/5

        //[HttpPost]
        //public ActionResult Edit(int id, FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add update logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        ////
        //// GET: /Charging/Delete/5

        //public ActionResult Delete(int id)
        //{
        //    return View();
        //}

        ////
        //// POST: /Charging/Delete/5

        //[HttpPost]
        //public ActionResult Delete(int id, FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add delete logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}
    }
}
